package com.example.proxytest.proxy.dynamicproxy.cglib;


import com.example.proxytest.proxy.MyTransaction;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/* ━━━━━━佛祖保佑━━━━━━
 *                  ,;,,;
 *                ,;;'(    社
 *      __      ,;;' ' \   会
 *   /'  '\'~~'~' \ /'\.)  主
 * ,;(      )    /  |.     义
 *,;' \    /-.,,(   ) \    码
 *     ) /       ) / )|    农
 *     ||        ||  \)
 *     (_\       (_\
 * ━━━━━━永无BUG━━━━━━
 * @author ：zjq
 * @date ：2020/9/7 14:37
 * @description: TODO
 * @version: V1.0
 * @slogan: 天下风云出我辈，一入代码岁月催
 */
public class PersonServiceInterceptor implements MethodInterceptor {
    //目标类
    private Object target;
    //增强类
    private MyTransaction myTransaction;

    public PersonServiceInterceptor() {
        System.out.println("cglib 构造方法 ");
    }

    //构造函数注入目标类和增强类
    public PersonServiceInterceptor(Object target, MyTransaction myTransaction) {
        this.target = target;
        this.myTransaction = myTransaction;
    }

    // 创建代理对象
    public Object createProxy() {
        Enhancer enhancer = new Enhancer();
        enhancer.setCallback(this);
        enhancer.setSuperclass(this.target.getClass());
        return enhancer.create();
    }


    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        myTransaction.beginTransaction();
        Object returnValue = method.invoke(this.target, objects);
        myTransaction.commit();
        return returnValue;
    }
}
